package com.lemon.common.web;

import com.lemon.common.accessory.domain.Accessory;
import com.lemon.common.accessory.service.AccessoryService;
import com.lemon.common.base64.BASE64DecodedMultipartFile;
import com.lemon.common.dto.Response;
import com.lemon.common.exception.ExceptionEnum;
import com.lemon.common.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 *
 * @author ymh
 * @date 2019-04-06 10:34
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private AccessoryService accessoryService;

    /**
     * 单个文件上传
     *
     * @param file
     * @return
     */
    @PostMapping
    public ResponseEntity<Response> upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BaseException(ExceptionEnum.UPLOAD_FILE_NOT_EXIST);
        }

        // 将 file 转换为 accessory
        Accessory accessory = new Accessory(file);
        File dest = new File(accessory.getAbsolutePath());
        // 如果父目录不存在就创建
        File parent = dest.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        try {
            // 上传文件
            file.transferTo(dest);
            // 文件信息保存到数据库中
            accessoryService.insert(accessory);
        } catch (IOException e) {
            throw new BaseException(ExceptionEnum.UPLOAD_FAILED);
        }

        return ResponseEntity.status(HttpStatus.OK).body(new Response(200, "文件上传成功", accessory));
    }

    /**
     * 上传 base64数据
     *
     * @param base64
     * @return
     */
    @PostMapping("/base64")
    public ResponseEntity<Response> uploadBase64(String base64) {
        MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(base64);

        if (file.isEmpty()) {
            throw new BaseException(ExceptionEnum.UPLOAD_FILE_NOT_EXIST);
        }

        // 将 file 转换为 accessory
        Accessory accessory = new Accessory(file);
        File dest = new File(accessory.getAbsolutePath());
        // 如果父目录不存在就创建
        File parent = dest.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        try {
            // 上传文件
            file.transferTo(dest);
            // 文件信息保存到数据库中
            accessoryService.insert(accessory);
        } catch (IOException e) {
            throw new BaseException(ExceptionEnum.UPLOAD_FAILED);
        }

        return ResponseEntity.status(HttpStatus.OK).body(new Response(200, "文件上传成功", accessory));
    }
}
